import { Avatar, Badge, Button, Descriptions, Divider, Space, Tag, Input, Select, Form, Modal, message } from "antd";
import {
  UserOutlined,
  EditOutlined, SaveOutlined, DeleteOutlined,
  PhoneOutlined, CalendarOutlined as HireDateIcon, HomeOutlined
} from '@ant-design/icons';
import { useState, useEffect } from "react";
import { Delete_Employee, Get_Dept, Get_DeptByPost, Update_Employee } from "../../service/organization";

export const EmployeeDetails = (props) => {

  const [form] = Form.useForm();
  const [editing, setEditing] = useState(false);
  const [originalData, setOriginalData] = useState(null);
  const currentEmp = props.data || {}; // 增加空对象默认值，避免null报错
  const [duty, setDuty] = useState([]); // 初始化岗位为数组
  const [departments, setDepartments] = useState([]); // 部门列表数据（扁平结构）

  // 初始化表单数据
  useEffect(() => {
    if (currentEmp) {
      setOriginalData({ ...currentEmp });
      form.setFieldsValue({
        name: currentEmp.name,
        gender: currentEmp.gender,
        phone: currentEmp.phone,
        hireDate: currentEmp.time,
        dept: currentEmp.d_id, // 使用d_id作为部门ID
        position: currentEmp.p_id, // 使用p_id作为岗位ID
        address: currentEmp.address || '',
        specialty: currentEmp.specialties || []
      });

      // 初始化岗位数据
      if (currentEmp.d_id) {
        handleDeptChange(currentEmp.d_id);
      }
    }
  }, [currentEmp, form]);

  // 切换到编辑模式
  const handleEdit = () => {
    setEditing(true);
  };

  //删除员工
  const handleDelete = async () => {

    const res = await Delete_Employee({ id: currentEmp.id });
    if (res.code == 0) {
      message.success("删除成功")
    
      props.onClose();
    }
  }

  // 取消编辑
  const handleCancel = () => {
    // 恢复原始数据
    if (originalData) {
      form.setFieldsValue({
        name: originalData.name,
        gender: originalData.gender,
        phone: originalData.phone,
        hireDate: originalData.time,
        dept: originalData.d_id, // 修复部门ID引用
        position: originalData.p_id, // 修复岗位ID引用
        address: originalData.address || '',
        specialty: originalData.specialties || []
      });
      // 恢复岗位数据
      if (originalData.d_id) {
        handleDeptChange(originalData.d_id);
      }
    }
    setEditing(false);
  };

  // 保存编辑
  const handleSave = async () => {
    try {
      const values = await form.validateFields();

      const res = await Update_Employee({ ...values, id: currentEmp.id });
      if (res.code == 0) {
        message.success("编辑成功")
        setEditing(false);
        props.onClose();

      }

    } catch (errorInfo) {
      console.error('保存失败:', errorInfo);
    }
  };

  // 处理擅长领域变更
  const handleSpecialtyChange = (tag, checked) => {
    const currentSpecialties = form.getFieldValue('specialty') || [];
    if (checked) {
      // 添加标签
      form.setFieldsValue({
        specialty: [...currentSpecialties, tag]
      });
    } else {
      // 移除标签
      form.setFieldsValue({
        specialty: currentSpecialties.filter(item => item !== tag)
      });
    }
  };

  // 递归函数：将嵌套的部门结构扁平化为一维数组
  const flattenDepartments = (departments) => {
    let result = [];
    departments.forEach(dept => {
      // 添加当前部门
      result.push(dept);
      // 如果有子部门，递归处理并合并结果
      if (dept.children && dept.children.length > 0) {
        result = result.concat(flattenDepartments(dept.children));
      }
    });
    return result;
  };

  // 部门变化时重新获取对应岗位
  const handleDeptChange = async (deptId) => {
    try {
      const res = await Get_DeptByPost({ id: deptId });
      if (res.code === 0) {
        const newDuty = res.data.map(d => ({
          value: d.id,
          label: d.name
        }));
        setDuty(newDuty);

        // 如果当前选中的岗位不在新岗位列表中，清除选中状态
        const currentPosition = form.getFieldValue('position');
        if (currentPosition && !newDuty.some(item => item.value === currentPosition)) {
          form.setFieldsValue({ position: undefined });
        }
      }
    } catch (error) {
      console.error("获取岗位数据失败:", error);
    }
  };

  useEffect(() => {
    const bind_dept = async () => {
      try {
        const res = await Get_Dept();
        // 将嵌套的部门结构转换为扁平结构
        const flatDepartments = flattenDepartments(res.data || []);
        setDepartments(flatDepartments);
      } catch (error) {
        console.error("获取部门数据失败:", error);
        Modal.error({
          title: "数据加载失败",
          content: "获取部门列表时发生错误，请稍后重试",
        });
      }
    };

    bind_dept();
  }, []); // 只在组件挂载时加载一次部门数据

  // 确保currentEmp存在，避免渲染错误
  if (!currentEmp) {
    return <div>加载中...</div>;
  }

  return (
    <div className="modal-box">
      {/* 头部信息 - 头像和基本身份信息 */}
      <div style={{ textAlign: 'center', marginBottom: 20 }}>
        <Avatar
          src={currentEmp.photo || undefined}
          size={80}
          style={{
            marginBottom: 10,
            fontSize: 32
          }}
          icon={!currentEmp.photo && <UserOutlined />} // 没有照片时显示默认图标
        />

        <h2 style={{ margin: 0 }}>{currentEmp.name}</h2>
        <p style={{ color: '#666', margin: 5 }}>
          {currentEmp.deptName} · {currentEmp.postName}
        </p>

        <Badge
          status={
            currentEmp.status === '在职' ? 'success' :
              currentEmp.status === '离职' ? 'processing' :
                currentEmp.status === '休假' ? 'warning' : 'error'
          }
          text={currentEmp.status}
        />
      </div>

      {/* 基本信息区域 */}
      <Divider orientation="left">基本信息</Divider>

      <Form form={form} layout="vertical">
        <Descriptions column={2} bordered>
          <Descriptions.Item label="账号">
            {currentEmp.account} {/* 工号通常不可编辑 */}
          </Descriptions.Item>

          <Descriptions.Item label="性别">
            {editing ? (
              <Form.Item
                name="gender"
                rules={[{ required: true, message: '请选择性别' }]}
                noStyle
              >
                <Select style={{ width: '100%' }}>
                  <Select.Option value="男">男</Select.Option>
                  <Select.Option value="女">女</Select.Option>
                </Select>
              </Form.Item>
            ) : (
              currentEmp.gender
            )}
          </Descriptions.Item>

          <Descriptions.Item label="联系电话" icon={<PhoneOutlined />}>
            {editing ? (
              <Form.Item
                name="phone"
                rules={[
                  { required: true, message: '请输入联系电话' },
                  { pattern: /^1[0-9]\d{9}$/, message: '请输入正确的手机号码' }
                ]}
                noStyle
              >
                <Input maxLength={11} />
              </Form.Item>
            ) : (
              currentEmp.phone
            )}
          </Descriptions.Item>

          <Descriptions.Item label="入职日期" icon={<HireDateIcon />}>

            {currentEmp.time}

          </Descriptions.Item>

          <Descriptions.Item label="所属部门">
            {editing ? (
              <Form.Item
                name="dept"
                rules={[{ required: true, message: '请选择部门' }]}
                noStyle
              >
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择部门"
                  onChange={handleDeptChange} // 部门变化时重新获取岗位
                >
                  {departments.map(dept => (
                    <Select.Option key={dept.key} value={dept.key}>
                      {dept.title}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            ) : (
              currentEmp.deptName
            )}
          </Descriptions.Item>

          <Descriptions.Item label="职称/岗位">
            {editing ? (
              <Form.Item
                name="position"
                rules={[{ required: true, message: '请选择岗位' }]}
                noStyle
              >
                <Select style={{ width: '100%' }} placeholder="请选择岗位">
                  {duty.map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            ) : (
              currentEmp.postName
            )}
          </Descriptions.Item>

          <Descriptions.Item label="住址" icon={<HomeOutlined />}>
            {editing ? (
              <Form.Item
                name="address"
                noStyle
              >
                <Input placeholder="请输入住址" />
              </Form.Item>
            ) : (
              currentEmp.address || '未填写'
            )}
          </Descriptions.Item>
        </Descriptions>


      </Form>

      {/* 操作按钮 */}
      <div style={{ marginTop: 20, textAlign: 'right' }}>
        <Space>
          {editing ? (
            <>
              <Button icon={<SaveOutlined />} type="primary" onClick={handleSave}>
                保存
              </Button>
              <Button onClick={handleCancel}>
                取消
              </Button>
            </>
          ) : (
            <Button icon={<EditOutlined />} onClick={handleEdit}>
              编辑信息
            </Button>
          )}

          <Button danger icon={<DeleteOutlined />} onClick={handleDelete}>
            删除员工
          </Button>
        </Space>
      </div>
    </div>
  );
};
